import { createApp } from 'vue'
import { createPinia } from 'pinia'
import { renderWithQiankun, qiankunWindow, type QiankunProps } from 'vite-plugin-qiankun/dist/helper'
import './style.css'
import App from './App.vue'
import router from './router'

function render(props: QiankunProps = {}) {
  const { container } = props
  const app = createApp(App)
  app.use(createPinia())
  app.use(router)
  container
    ? app.mount(container.querySelector('#app') as HTMLElement)
    : app.mount('#app')
  return app
}

function initApp() {
  if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
    console.log('%c 独立渲染', 'color: blue; font-size: 20px;')
    render()
    return
  }
  renderWithQiankun({
    mount(props) {
      console.log('%c qiankun 渲染', 'color: blue; font-size: 20px;')
      console.log(props)
      // 保存主应用传递的actions，用于通信
      if (props.actions) {
        if ((window as any).__MICRO_APP_ENVIRONMENT__) {
          (window as any).__MICRO_APP_ENVIRONMENT__.globalState = props
        }
      }
      render(props)
    },
    bootstrap() {
      console.log('bootstrap')
    },
    unmount(props) {
      console.log('unmount', props)
      // 清理应用实例
      const container = props.container || document
      const appElement = container.querySelector('#app')
      if (appElement) {
        const app = createApp({})
        app.unmount()
      }
    },
    update(props) {
      console.log('update', props)
    },
  })
}

initApp()
